package com.zw.yzk.kabu.view.activity;

import android.app.Dialog;
import android.content.DialogInterface;
import android.os.Bundle;
import android.support.annotation.Nullable;
import android.support.v4.view.PagerAdapter;
import android.support.v4.view.ViewPager;
import android.support.v7.app.AlertDialog;
import android.view.MotionEvent;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.RelativeLayout;
import android.widget.TextView;
import butterknife.Bind;
import com.bumptech.glide.Glide;
import com.zw.yzk.kabu.R;
import com.zw.yzk.kabu.base.BaseActivity;
import com.zw.yzk.kabu.constant.ActivityConstant;
import com.zw.yzk.kabu.internal.component.DaggerSkinComponent;
import com.zw.yzk.kabu.internal.module.ActivityModule;
import com.zw.yzk.kabu.internal.module.SkinModule;
import com.zw.yzk.kabu.management.LoadingDialogManager;
import com.zw.yzk.kabu.management.ToastManager;
import com.zw.yzk.kabu.management.ToolbarBuilder;
import com.zw.yzk.kabu.model.SkinModel;
import com.zw.yzk.kabu.presenter.SkinPackagePresenter;
import com.zw.yzk.kabu.view.view.SkinPackageView;

import javax.inject.Inject;
import java.util.List;

public class SkinPackageActivity extends BaseActivity implements SkinPackageView {

    @Bind(R.id.pager_layout)
    RelativeLayout viewPagerContainer;
    @Bind(R.id.view_pager)
    ViewPager viewPager;
    @Bind(R.id.tv_title)
    TextView title;
    @Bind(R.id.tv_fee)
    TextView fee;
    @Bind(R.id.btn_action)
    Button action;
    @Bind(R.id.right_image)
    View rightImg;

    @Inject
    SkinPackagePresenter presenter;

    private SkinModel skin;
    private String[] btnStatus;

    @Override
    public int getLayoutId() {
        return R.layout.activity_skin_package;
    }

    @Override
    public void iniToolbar(BaseActivity activity) {
        String title = getIntent().getStringExtra(ActivityConstant.SKIN_PACKAGE_NAME);

        ToolbarBuilder
                .createBuilder(this)
                .setTitle(title)
                .setRightImage(R.drawable.ic_delete)
                .build();
        rightImg.setVisibility(View.INVISIBLE);
    }

    @Override
    public void initComponent() {
        DaggerSkinComponent.builder()
                .applicationComponent(getApplicationComponent())
                .activityModule(new ActivityModule(this))
                .skinModule(new SkinModule())
                .build()
                .inject(this);
        presenter.setView(this);
    }

    @Override
    public void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);

        btnStatus = getResources().getStringArray(R.array.skin_actions);
        presenter.getSkinPackage(getIntent().getIntExtra(ActivityConstant.SKIN_PACKAGE_ID, 0));
        LoadingDialogManager.getInstance().showLoadingDialog(this);
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();

        presenter.destroy();
    }

    @Override
    public void showSkinPackage(SkinModel skin) {
        this.skin = skin;
        title.setText(skin.getName());
        if(skin.getDiscountedPrice() == 0){
            fee.setText(getResources().getString(R.string.skin_fee_free));
        }else{
            fee.setText(String.valueOf(skin.getDiscountedPrice()));
        }

        viewPager.setAdapter(new MyPagerAdapter(skin.getIntroduces()));
        // to cache all page, or we will see the right item delayed
        viewPager.setOffscreenPageLimit(5);
        viewPager.setPageMargin(getResources().getDimensionPixelSize(R.dimen.activity_horizontal_margin));
        viewPager.setOnPageChangeListener(new MyOnPageChangeListener());

        viewPagerContainer.setOnTouchListener(new View.OnTouchListener() {

            @Override
            public boolean onTouch(View v, MotionEvent event) {
                // dispatch the events to the ViewPager, to solve the problem that we can swipe only the middle view.
                return viewPager.dispatchTouchEvent(event);
            }
        });
    }

    @Override
    public void fetchFailed() {

    }

    @Override
    public void skinPackageNotReady() {
        presenter.getSkinPackage(getIntent().getIntExtra(ActivityConstant.SKIN_PACKAGE_ID, 0));
        LoadingDialogManager.getInstance().showLoadingDialog(this);
    }

    int state = -1;
    @Override
    public void showBtnState(int state){
        if(this.state == state) return;
        this.state = state;

        switch (state){
            case 0:
                rightImg.setVisibility(View.INVISIBLE);
                action.setOnClickListener(new View.OnClickListener() {
                    @Override
                    public void onClick(View v) {
                        if( skin.getDiscountedPrice() > 0.0 ){
                            showNotFeeTips();
                            return;
                        }
                        LoadingDialogManager.getInstance().showLoadingDialog(SkinPackageActivity.this);
                        presenter.download();
                    }
                });
                action.setEnabled(true);
                LoadingDialogManager.getInstance().dismissLoadingDialog();
                break;
            case 1:
                rightImg.setVisibility(View.INVISIBLE);
                Dialog dialog = LoadingDialogManager.getInstance().showLoadingDialog(this);
                if(dialog != null) {
                    dialog.setOnCancelListener(new DialogInterface.OnCancelListener() {
                        @Override
                        public void onCancel(DialogInterface dialog) {
                            presenter.cancelDownload();
                        }
                    });
                }
                action.setEnabled(false);
                break;
            case 2:// 如果皮肤存在
                rightImg.setVisibility(View.VISIBLE);
                rightImg.setOnClickListener(new View.OnClickListener() {
                    @Override
                    public void onClick(View v) {
                        presenter.initSkin();
                    }
                });
                action.setOnClickListener(new View.OnClickListener() {
                    @Override
                    public void onClick(View v) {
                        presenter.loadSkin();
                    }
                });
                action.setEnabled(true);
                LoadingDialogManager.getInstance().dismissLoadingDialog();
                break;
            case 3: // 如果皮肤在使用
                rightImg.setVisibility(View.INVISIBLE);
                action.setEnabled(false);
                LoadingDialogManager.getInstance().dismissLoadingDialog();
                break;
        }
        if(state < btnStatus.length)
            action.setText(btnStatus[state]);
    }

    @Override
    public void showProgress(String progress) {
        action.setText(progress);
    }

    @Override
    public void showDownloadError() {
        ToastManager.getInstance().showToast(this, getResources().getString(R.string.skin_download_error));
    }

    @Override
    public void showDownloadComplete() {

    }

    @Override
    public void onDownloadCanceled() {

    }

    // TODO:
    private void showNotFeeTips(){
        new AlertDialog.Builder(SkinPackageActivity.this)
                .setCancelable(true)
                .setTitle(R.string.buy_skin_tip_tile)
                .setMessage(R.string.buy_skin_only_free)
                .setPositiveButton(R.string.confirm, null)
                .show();
    }

    class MyPagerAdapter extends PagerAdapter {

        List<SkinModel.SkinIntroduceModel> models;

        MyPagerAdapter(List<SkinModel.SkinIntroduceModel> models){
            this.models = models;
        }

        @Override
        public int getCount() {
            return models.size();
        }

        @Override
        public boolean isViewFromObject(View view, Object object) {
            return (view == object);
        }

        @Override
        public Object instantiateItem(ViewGroup container, int position) {
            ImageView imageView = new ImageView(SkinPackageActivity.this);
            ((ViewPager)container).addView(imageView, position);

            Glide.with(SkinPackageActivity.this)
                    .load(models.get(position).getImg())
                    .fitCenter()
                    .error(R.drawable.ic_gf_default_photo)
                    .placeholder(R.drawable.ic_gf_default_photo)
                    .into(imageView);

            return imageView;
        }

        @Override
        public void destroyItem(ViewGroup container, int position, Object object) {
            ((ViewPager)container).removeView((ImageView)object);
        }
    }

    public class MyOnPageChangeListener implements ViewPager.OnPageChangeListener {

        @Override
        public void onPageSelected(int position) {

        }

        @Override
        public void onPageScrolled(int position, float positionOffset, int positionOffsetPixels) {
            // to refresh frameLayout
            if (viewPagerContainer != null) {
                viewPagerContainer.invalidate();
            }
        }

        @Override
        public void onPageScrollStateChanged(int arg0) {}
    }
}
